package com.sakiko.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * projectName: com.sakiko.config
 *
 * @author: Yang
 * description: redis 配置类
 * time: 2025/8/2 15:44
 */

@SpringBootConfiguration
public class RedisConfiguration {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        GenericJackson2JsonRedisSerializer jsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();

        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setValueSerializer(RedisSerializer.string());
        redisTemplate.setHashKeySerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    // 加载 lua脚本，设置返回值类型 boolean ==>  脚本 return true | false
    // 优势: 比第二种便于维护
    @Bean
    public RedisScript<Boolean> script() {
        Resource scriptSource = new ClassPathResource("lua/test.lua");
        return RedisScript.of(scriptSource, Boolean.class);
    }

    // 加载 lua脚本，第二种写法
//    @Bean
//    public RedisScript<Boolean> script() {
//        String script = "local temp = redis.call('get', KEYS[1])\n" +
//                "if temp == ARGV[1]\n" +
//                "    then redis.call('set', KEYS[1], ARGV[2])\n" +
//                "    return true\n" +
//                "end\n" +
//                "return false";
//
//        DefaultRedisScript defaultRedisScript =
//                new DefaultRedisScript(script, Boolean.class);
//
//        return defaultRedisScript;
//    }
}
